package tools;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import com.lexicalscope.jewel.cli.CliFactory;
import com.lexicalscope.jewel.cli.Option;

/**
 * Hello world!
 */
public class SearchBean {
	private static Params params;

	public static void main(String[] args) throws IOException {
		params = CliFactory.parseArguments(Params.class, args);

		File folder = new File(params.getFolder());
		for (File file : FileUtils.listFiles(folder, null, true)) {
			System.out.println(file.getAbsolutePath());
			JarFile jar = new JarFile(file);
			Enumeration<JarEntry> iter = jar.entries();
			while (iter.hasMoreElements()) {
				JarEntry entry = iter.nextElement();
				if (entry.getName().endsWith(".xml")) {
					InputStream stream = jar.getInputStream(jar
							.getJarEntry(entry.getName()));
					readStream(entry.getName(), stream);
				}
			}
		}
	}

	private static void readStream(String name, InputStream stream)
			throws IOException {
		String s = IOUtils.toString(stream, "UTF-8");
		if (s.contains(params.getSearch())) {
			System.out.println(name);
		}
	}

	public static interface Params {
		@Option
		String getFolder();

		@Option
		String getSearch();

		@Option
		String getRoot();
	}
}
